package com.framework.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;

import static org.openqa.selenium.support.ui.ExpectedConditions.textToBePresentInElement;

public class MainPage extends AnyPage {

    public MainPage(PageManager pages) {
        super(pages);
    }

    @FindBy(css = "nav a[href $= '?go=add']")
    private WebElement addMovie;

    @FindBy(id = "q")
    private WebElement searchField;

    @FindBy(id = "results")
    private WebElement resultsBlock;

    @FindBy(xpath = "//*[@id=\"results\"]/a[1]/div/div[2]")
    private WebElement firstElementInResults;

    public MainPage ensurePageLoaded() {
        wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id("q")));
        return this;
    }

    public MainPage ensureContentLoaded() {
        wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id("loading")));
        wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id("results")));
        return this;
    }

    public AddMoviePage clickAddMovieButton() {
        addMovie.click();
        return pages.addMoviePage;
    }

    public MainPage clickSearch() {
        searchField.click();
        return this;
    }

    public MainPage clearSearchField() {
        searchField.clear();
        return this;
    }

    public MainPage setQuery(String text) {
        searchField.sendKeys(text);
        return this;
    }

    public MainPage pressEnterInSearch() {
        searchField.sendKeys(Keys.RETURN);
        return this;
    }

    public MainPage SearchMovie(String text) {
        clickSearch().clearSearchField().setQuery(text).pressEnterInSearch();
        return this;
    }

    public boolean checkNoMoviesFound() {
        return wait.until(textToBePresentInElement(resultsBlock, "No movies where found."));
    }

    public boolean checkFirstMovieInResults(String title) {
        return firstElementInResults.getText().contentEquals(title);
    }
}
